package com.eastfair.venuebooking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.venuebooking.dao.QuotationDetailMapper;
import com.eastfair.venuebooking.dto.QuotationDetailDTO;
import com.eastfair.venuebooking.dto.QuotationDetailQuery;
import com.eastfair.venuebooking.dto.SalesAnalysisDTO;
import com.eastfair.venuebooking.entity.BusinessOpportunity;
import com.eastfair.venuebooking.entity.QuotationDetail;
import com.eastfair.venuebooking.service.QuotationDetailService;
import com.eastfair.venuebooking.vo.QuotationDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 报价书详情
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Service
public class QuotationDetailServiceImpl extends SuperServiceImpl<QuotationDetailMapper, QuotationDetail> implements QuotationDetailService {

    @Resource
    private QuotationDetailMapper quotationDetailMapper;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<QuotationDetail> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(QuotationDetail model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setTenantId(ContextUtil.getTenantId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public List<String> getSpaceNamesByExhibitionId(Long exhibitionId) {
        return baseMapper.getSpaceNamesByExhibitionId(exhibitionId);
    }

    @Override
    public List<QuotationDetailVO> listQuotationDetailVOs(QuotationDetailQuery query) {
        log.info("listQuotationDetailVOs - 查询报价书详情列表, query={}", query);

        QueryWrapper<QuotationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(query.getQuotitionId() != null, QuotationDetail::getQuotitionId, query.getQuotitionId())
                .eq(QuotationDetail::getIsDeleted, BusinessConstant.NO);
        List<QuotationDetail> quotationDetailList = list(queryWrapper);
        return quotationDetailList
                .stream()
                .map(quotationDetail -> BeanUtil.toBean(quotationDetail, QuotationDetailVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<QuotationDetailVO> listQuotationDetailVOsByQuotationId(Long quotationId) {
        log.info("listQuotationDetailVOsByQuotationId - 报价书id查询报价书详情列表, quotationId={}", quotationId);
        return quotationDetailMapper.listQuotationDetailVOsByQuotationId(quotationId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<QuotationDetailDTO> list, Long quotationId) {
        log.info("saveBatch - 批量保存报价书详情, list={}, quotationId={}", list, quotationId);
        if (list == null || list.isEmpty()) {
            return false;
        }
        List<QuotationDetail> quotationDetailList = toQuotationDetails(list, quotationId);
        quotationDetailList.forEach(this::save);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateBatch(List<QuotationDetailDTO> list, Long quotationId) {
        log.info("saveOrUpdateBatch - 批量保存或更新报价书详情, list={}, quotationId={}", list, quotationId);
        if (list == null || list.isEmpty()) {
            return false;
        }
        // 分组，分为待更新和待新增列表
        List<QuotationDetail> quotationDetailList = toQuotationDetails(list, quotationId);
        Map<Boolean, List<QuotationDetail>> quotationDetailDTOMap = quotationDetailList
                .stream()
                .collect(Collectors.groupingBy(quotationDetail -> quotationDetail.getId() == null));
        // 保存新添加的报价书详情
        List<QuotationDetail> saveQuotationDetailDTOList = quotationDetailDTOMap.get(true);
        saveBatch(saveQuotationDetailDTOList);
        // 更新已存在的报价书详情
        List<QuotationDetail> updateQuotationDetailDTOList = quotationDetailDTOMap.get(false);
        updateBatchById(updateQuotationDetailDTOList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByQuotationIds(List<Long> quotationIds) {
        QueryWrapper<QuotationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(QuotationDetail::getIsDeleted, BusinessConstant.DELETE_NO)
                .in(QuotationDetail::getQuotitionId, quotationIds);
        List<QuotationDetail> quotationDetailList = list(queryWrapper);
        return removeByIdsOfLogic(quotationDetailList);
    }

    /**
     * 获取计价面积
     * @param salesAnalysisDTO
     * @return
     */
    @Override
    public Integer getSpaceLeaseStatisticsTotalData(SalesAnalysisDTO salesAnalysisDTO) {

        QueryWrapper<QuotationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(QuotationDetail::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(Objects.nonNull(salesAnalysisDTO.getSpaceId()),QuotationDetail::getSpaceId,salesAnalysisDTO.getSpaceId())
                .between(Objects.nonNull(salesAnalysisDTO.getStartTime())
                                && Objects.nonNull(salesAnalysisDTO.getEndTime()),
                        QuotationDetail::getCreateTime, salesAnalysisDTO.getStartTime(), salesAnalysisDTO.getEndTime());
        List<QuotationDetail> quotationDetailList = list(queryWrapper);
        Integer countStatistics=0;
        if(Objects.nonNull(quotationDetailList) && quotationDetailList.size()>0){
          for (QuotationDetail s:quotationDetailList){
             countStatistics+=Integer.valueOf(s.getPriceArea());

          }

        }
        return countStatistics;
    }

    /**
     * QuotationDetailDTO 转为 QuotationDetailDTO 列表
     *
     * @param list        QuotationDetailDTO 列表
     * @param quotationId 报价书id
     * @return QuotationDetail 列表
     */
    private List<QuotationDetail> toQuotationDetails(List<QuotationDetailDTO> list, Long quotationId) {
        return list
                .stream()
                .map(quotationDetailDTO -> {
                    QuotationDetail quotationDetail = BeanUtil.toBean(quotationDetailDTO, QuotationDetail.class);
                    quotationDetail.setQuotitionId(quotationId);
                    return quotationDetail;
                })
                .collect(Collectors.toList());
    }
}
